package cn.com.surker.system.controller;

import cn.com.surker.common.AbstractController;
import cn.com.surker.common.Code;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.entity.SysPosition;
import cn.com.surker.system.entity.SysRole;
import cn.com.surker.system.entity.SysUser;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.system.service.SysPositionService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.transaction.RollbackException;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author luotao
 * @date 2022/11/18
 */
@RestController
@RequestMapping("/sys_position")
public class SysPositionController  extends AbstractController {

	@Resource
	private SysPositionService sysPositionService;

	// 新增岗位
	@RequestMapping(value = "/add",method = RequestMethod.PUT)
	@ResponseBody
	@Transactional(rollbackFor = RollbackException.class,propagation = Propagation.REQUIRED)
	public RestResultDto add(SysPosition position, BindingResult results){
		CacheUser user = getUser();
		if(user == null){
			return RestResultDto.fail(Code.UN_USER_INFO);
		}
		if (results.hasErrors()){
			String defaultMessage = results.getFieldError().getDefaultMessage();
			return RestResultDto.fail(defaultMessage);
		}
		// 查询岗位名称是否存在过
		String positionName = position.getName();
		Boolean exist = sysPositionService.isExist(positionName);
		if(exist){
			return RestResultDto.fail("岗位已存在");
		}
		boolean save = sysPositionService.save(position);
		if(save){
			// 新增岗位的时候,也新增一个角色
			List<SysRole> roles = roleService.findByName(positionName);
			if(roles == null || roles.isEmpty()){
				SysRole role = new SysRole();
				role.setName(positionName);
				role.setRoleGroup(positionName);
				role.setRemark("新增岗位[" + positionName +"]时,同步过来的数据");
				roleService.saveInit(role);
				return RestResultDto.success();
			}
			return RestResultDto.success();
		}else {
			return RestResultDto.fail();
		}
	}
	// 修改岗位
	@RequestMapping(value = "/update/{id}",method = RequestMethod.PUT)
	@ResponseBody
	@Transactional(rollbackFor = RollbackException.class,propagation = Propagation.REQUIRED)
	public RestResultDto update(@PathVariable Long id, SysPosition sysPosition, BindingResult results){
		CacheUser user = getUser();
		if(user == null){
			return RestResultDto.fail(Code.UN_USER_INFO);
		}
		if(id == null){
			return RestResultDto.fail(Code.PARAM_EMPTY);
		}
		if (results.hasErrors()){
			String defaultMessage = results.getFieldError().getDefaultMessage();
			return RestResultDto.fail(defaultMessage);
		}
		@NotNull(message = "请输入岗位名称") String positionName = sysPosition.getName();
		Boolean exist = sysPositionService.isExist(positionName);
		if(exist){
			return RestResultDto.fail("岗位名已存在");
		}
		// 查询旧岗位信息
		SysPosition oldPosition = sysPositionService.getById(id);
		if(oldPosition == null){
			return RestResultDto.fail("待修改的岗位信息不存在");
		}
		sysPosition.setId(id);
		boolean b = sysPositionService.updateById(sysPosition);
		if(b){
			// 更新成功,修改同名的角色
			List<SysRole> roles = roleService.findByName(oldPosition.getName());
			if(roles == null || roles.isEmpty()){
				// 没有查询到旧角色,新增
				SysRole role = new SysRole();
				role.setName(positionName);
				role.setRoleGroup(positionName);
				role.setRemark("修改岗位[" + positionName +"]时,同步过来的数据");
				roleService.saveInit(role);
			}else {
				// 存在旧角色
				for (SysRole record : roles){
					// 修改旧角色
					record.setName(positionName);
					String remark = record.getRemark();
					remark += ";原岗位("+oldPosition.getName()+")变动,更改为[" + positionName + "]";
					record.setRemark(remark);
					roleService.update(record);
				}
			}
			return RestResultDto.success();
		}else {
			return RestResultDto.fail();
		}
	}

	// 删除岗位 如果该岗位有用户，则不能删除
	@RequestMapping(value = "/delete/{id}",method = RequestMethod.DELETE)
	@ResponseBody
	@Transactional(rollbackFor = RollbackException.class,propagation = Propagation.REQUIRED)
	public RestResultDto delete(@PathVariable Long id){
		if(id == null){
			return RestResultDto.fail(Code.PARAM_EMPTY);
		}
		// 查询角色
		SysPosition oldPosition = sysPositionService.getById(id);
		if(oldPosition == null){
			return RestResultDto.fail("待操作的岗位信息不存在");
		}
		// 验证是否有绑定信息
		List<SysUser> users = userService.queryUsersByOrgPos(null, id,null);
		if(users != null && !users.isEmpty()){
			return RestResultDto.fail("该岗位下存在绑定用户，不能删除");
		}
		Integer i = sysPositionService.delete(id);
		if(i > 0){
			// 删除岗位后,禁用角色
			List<SysRole> roles = roleService.findByName(oldPosition.getName());
			if(roles != null && !roles.isEmpty()) {
				// 存在旧角色
				for (SysRole record : roles){
					// 修改旧角色
					String remark = record.getRemark();
					remark += ";原岗位("+oldPosition.getName()+")删除,同步删除本角色数据";
					record.setRemark(remark);
					record.setStatus(StateEnum.DISABLED.getCode());
					roleService.update(record);
				}
			}
			return RestResultDto.success();
		}else {
			return RestResultDto.fail();
		}
	}


	// 查看岗位列表
	@RequestMapping(value = "/list",method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto list(String name){
		List<SysPosition> sysPositions =  sysPositionService.findList(name);
		return RestResultDto.success(sysPositions);
	}

	/**
	 * 分页查询数据
	 * @param name
	 * @param pageIndex
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/page",method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto page(String name,Integer pageIndex,Integer limit){
		IPage<SysPosition> page = sysPositionService.page(name, pageIndex, limit);
		return RestResultDto.success(page);
	}
}
